<template>
  <!-- 顶部导航 -->
  <div class="mb-20px">
    <div class="flex items-center gap-12px">
      <el-button type="text" @click="goBack" class="flex items-center gap-8px">
        <Icon icon="ep:arrow-left" />
        返回
      </el-button>
      <div class="h-20px w-2px bg-blue-500"></div>
      <span class="font-500 text-14px">题库名称: {{ storeName || '未知题库' }}</span>
    </div>
  </div>

  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <!-- <el-form-item label="题干" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入题干"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <!-- <el-button @click="handleQuery"> <Icon icon="ep:search" class="mr-5px" /> 查询 </el-button> -->
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" class="mr-5px" /> 重置 </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['pm:tm:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
          v-hasPermi="['pm:tm:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 操作工具栏 -->
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="题干" prop="queContent" min-width="200" show-overflow-tooltip />
      <el-table-column label="区分度" prop="discrimination" width="100" align="center" />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['pm:tm:update']"
          >
            修改
          </el-button>
          <!-- <el-button
            link
            type="primary"
            @click="handleCopy(scope.row)"
            v-hasPermi="['pm:tm:create']"
          >
            复制
          </el-button> -->
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['pm:tm:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 表单弹窗：添加/修改 -->
    <QuestionForm ref="formRef" @success="getList" />
    <!-- 导入弹窗 -->
    <QuestionImportForm ref="importFormRef" @success="getList" />
  </ContentWrap>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as QuestionApi from '@/api/pm/tm'
import QuestionForm from './QuestionForm.vue'
import QuestionImportForm from './QuestionImportForm.vue'
import { useTagsView } from '@/hooks/web/useTagsView'
import { useRouter } from 'vue-router'
import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({ name: 'PmTm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  storeId: undefined as number | undefined,
  name: undefined as string | undefined
})
const selectedIds = ref<number[]>([]) // 选中行的 id 数组
const storeName = ref('') // 题库名称

const queryFormRef = ref() // 搜索的表单
const formRef = ref() // 表单 Ref
const importFormRef = ref() // 导入表单 Ref

// 标签页操作
const router = useRouter()
const { delView } = useTagsViewStore()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await QuestionApi.getQuestionPage({
      page: queryParams.pageNo,
      limit: queryParams.pageSize,
      storeId: queryParams.storeId,
      keyWord: queryParams.name
    })
    list.value = data.list
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, queryParams.storeId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await QuestionApi.deleteQuestion(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 复制按钮操作 */
const handleCopy = (row: any) => {
  openForm('create', row.id)
}

/** 批量删除按钮操作 */
const handleBatchDelete = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认删除选中的题目？')
    // 发起删除
    await QuestionApi.batchDeleteQuestion(selectedIds.value.join(','))
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    // 清空选择
    clearSelection()
  } catch {}
}

/** 选择行 */
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item.id)
}

/** 清空选择 */
const clearSelection = () => {
  selectedIds.value = []
}

/** 排序变化 */
const handleSortChange = (sort: any) => {
  // 处理排序逻辑
}

/** 返回上一页 */
const goBack = () => {
  // 先删除当前页签
  delView(unref(router.currentRoute))
  // 跳转到列表页
  router.push({ path: '/pm/catstore' })
}

/** 初始化 **/
onMounted(() => {
  // 从路由参数获取storeId
  const route = useRoute()
  if (route.query.storeId) {
    queryParams.storeId = Number(route.query.storeId)
  }
  // 获取题库名称（可以从路由参数或其他方式获取）
  if (route.query.storeName) {
    storeName.value = String(route.query.storeName)
  }
  getList()
})
</script>
